

def shift_ra(ira):
    if ira < -6:
        ra = ira + 24 + 24
    else:
        ra = ira + 24
    return ra
	
from ut_misc import js_r

def output_as_py(fn,segs):
    if 1:
        f=open(fn,'w')
        txt='segs=[\n'
        for seg in segs:
            txt+='\t[\n'
            d=0
            for ra,dec in seg:
                txt+='(%.2f,%.2f),' % (ra,dec)
                d+=1
                if d==10:
                    txt+='\n'
                    d=0
            txt+='\t],\n'
        txt+=']\n'
        f.write(txt)
        f.close()


class RAXS:
    def __init__(self):
        self.raxs=[]
        self.raxs_up=None
        self.txt=''
        self.txt1=''
        self.ix=0
        self.min=100
        self.max=-100
        self.ix_max=0
        self.ix_min=0
    
    def add(self,ra,dec):
        if ra > self.max:
            self.max=ra
            self.ix_max=self.ix
        if ra < self.min:
            self.min=ra
            self.ix_min=self.ix
        
        self.txt+='%d %.2f,%.2f\n' % (self.ix,ra,dec)
        if len(self.raxs)==0:
            self.raxs.append(ra)
            self.txt1+='%d %.2f\n' % (self.ix,ra)
            self.ix+=1
            return
        
        if self.raxs_up is None:
            if ra >= self.raxs[-1]:
                self.raxs_up=True
                self.txt1+='%d %.2f up\n' % (self.ix,ra)
            else:
                self.raxs_up=False
                self.txt1+='%d %.2f down\n' % (self.ix,ra)
            self.raxs.append(ra)
            self.ix+=1
            return
        
        if ra > self.raxs[-1]:
            if self.raxs_up == False:
                self.raxs_up=True
                self.txt1+='%d %.2f --\n' % (self.ix-1,self.raxs[-1])         
                self.txt1+='%d %.2f up\n' % (self.ix,ra)
        elif ra < self.raxs[-1]:
            if self.raxs_up==True:
                self.raxs_up=False
                self.txt1+='%d %.2f ++\n' % (self.ix-1,self.raxs[-1])         
                self.txt1+='%d %.2f down\n' % (self.ix,ra)
        self.raxs.append(ra)
        self.ix+=1
        
    def report(self,fn):
        f=open(fn,'w')
        f.write(self.txt1)
        f.write('min:%.2f (%d)\n' % (self.min, self.ix_min))   
        f.write('max:%.2f (%d)\n' % (self.max, self.ix_max))
        f.write('#----------\n')
        f.write(self.txt)
        f.close()
        """
class RA_DEC_SEG:
    def __init__(self):
        self.seg=[]
        self.segs=[]
        self.ra_min=99
        self.ra_max=0
        
    def add(self,ra,dec):
        if len(self.seg)==0:
            self.seg.append((ra,dec))
            return
        if abs(ra - self.seg[-1][0]) >2:
            self.segs.append(self.seg)
            self.seg=[]
        self.seg.append((ra,dec))
        
    def commit(self):
        if len(self.seg)>0:
            self.segs.append(self.seg)
            self.seg=[]
            
    def get_segs(self):
        self.commit()
        return self.segs
    
    def output_as_py(self,fn):
        self.commit()
        output_as_py(fn, self.segs)
        skip="""
        f=open(fn,'w')
        txt='segs=[\n'
        for seg in self.segs:
            txt+='\t[\n'
            d=0
            for ra,dec in seg:
                txt+='(%.2f,%.2f),' % (ra,dec)
                d+=1
                if d==10:
                    txt+='\n'
                    d=0
            txt+='\t],\n'
        txt+=']\n'
        f.write(txt)
        f.close()
        """
        
    def report(self,fn):
        self.commit()
        f = open(fn,'w')
        s=0
        txt1=''
        txt=''
        for seg in self.segs:
            ras = list(zip(*seg))[0]
            ra_min = min(ras)
            ra_max = max(ras)
            txt1+='seg %d:(%.2f,%.2f) ~ (%.2f,%.2f)' %\
                (s, seg[0][0],seg[0][1],seg[-1][0],seg[-1][1])
            txt1+= ' ra min:%.2f max:%.2f\n' % (ra_min,ra_max)
            
            txt+='seg %d\n' % s
            for ra,dec in seg:
                txt+='(%.2f,%.2f),' % (ra,dec)
            txt+='\n'
            s+=1
        f.write(txt1)
        f.write(txt)
        f.close()
        
class RA_DEC_XS:
    def __init__(self):
        #self.dictx={}
        self.dictsegs={}
        
    def add(self,i,j,ra,dec):
        #print('ra_dec_xs add i:%d j:%d' % (i,j))
        if not i in self.dictsegs:
            #self.dictx[i]={}
            self.dictsegs[i]={}
        if not j in self.dictsegs[i]:
            #self.dictx[i][j]=1
            self.dictsegs[i][j]= RA_DEC_SEG()
        #self.dictx[i][j].add(ra,dec)
        self.dictsegs[i][j].add(ra,dec)
        
    def commit(self,fnx):
        ixs = list(self.dictsegs.keys())
        for i in ixs:
            segxs=[]
            jxs = list(self.dictsegs[i].keys())
            for j in jxs:
                #fn = fnx % (i,j) + '.dat'
                #self.dictx[i][j].report(fn)
                fn1 = fnx % (i,j) + 'seg.dat'
                self.dictsegs[i][j].report(fn1)
                if i==1:
                    fn2 = fnx % (i,j) + '.py'
                    self.dictsegs[i][j].output_as_py(fn2)
                else:
                    segs = self.dictsegs[i][j].get_segs()
                    for seg in segs:
                        segxs.append(seg)
            if i> 1:
                output_as_py(fnx % (i,0)+'.py',segxs)
                
def get_raxs_1_data():
    from raxs_1 import seg
    data=[]
    for ra,dec in seg:
        y = dec_to_y(dec)
        x = RA_to_x(g_share.x0, ra)
        data.append((x,y))
        
    return data

def get_raxs_1_n_segs():
    from raxs_1_n import segs
    return segs
def get_raxs_2_n_segs():
    from raxs_2_n import segs
    return segs
def get_raxs_3_n_segs():
    from raxs_3_n import segs
    return segs
def get_raxs_4_n_segs():
    from raxs_4_n import segs
    return segs
def get_raxs_5_n_segs():
    from raxs_5_n import segs
    return segs

get_raxs_n_n=[
    get_raxs_1_n_segs,
    get_raxs_2_n_segs,
    get_raxs_3_n_segs,
    get_raxs_4_n_segs,
    get_raxs_5_n_segs,
]

def convert_raxs_n_n_data(segs):
    datas=[]
    for seg in segs:
        data=[]
        for ra,dec in seg:
     
            y = dec_to_y(dec)
            x = RA_to_x(g_share.x0, ra)
            data.append((x,y))
        datas.append(data)
        
    return datas,segs

        
def get_raxs_n_data():
    n=1
    dicts={}
    for get_raxs in get_raxs_n_n:
        segs = get_raxs()
        print('get_raxs_n_data n:%d len:%d' % (n,len(segs)))
        dicts[n]= convert_raxs_n_n_data(segs)
        n+=1
    return dicts

skip="""
def get_raxs_1_n_data():
    from raxs_1_n import segs
    datas=[]
    for seg in segs:
        data=[]
        for ra,dec in seg:
            y = dec_to_y(dec)
            x = RA_to_x(g_share.x0, ra)
            data.append((x,y))
        datas.append(data)
        
    return datas

def get_raxs_2_n_data():
    from raxs_2_n import segs
    datas=[]
    for seg in segs:
        data=[]
        for ra,dec in seg:
            y = dec_to_y(dec)
            x = RA_to_x(g_share.x0, ra)
            data.append((x,y))
        datas.append(data)
        
    return datas,segs
"""

skip="""
def get_raxs_0_data():
    from raxs_0 import seg
    data=[]
    for ra,dec in seg:
        y = dec_to_y(dec)
        x = RA_to_x(g_share.x0, ra)
        data.append((x,y))
    return data
"""

def draw_milkyway_lin(paper):
    layer= paper.add_layer(name='mw')
    draw=layer.draw
    data = js_r(config.mw_path)
    color_sky = config.color_sky_day
    i=0
    j=0
    dtss={}
    ra_dec_xs=RA_DEC_XS()
    
    for s in data['features']:
        j=0
        i+=1
        dtss[i]=[]
        #print(i)
        #print(s.keys())
        keys = s.keys()
        for key in keys:
            if key !='geometry':
                pass
                #print(key, s[key])
            else:
                #print('geometry type:', s['geometry']['type'])
                coords =s['geometry']['coordinates']
                #print('coordinates type:', type(coords))
                for v1 in coords:
                    for v2 in v1:
                        dts=[]
                        for v3 in v2:
                            #print('\t[%s..]..%d' % (v3[:5], len(v3)))
                            ra_deg,dec = v3[0], v3[1]
                            ra =ra_deg/15.0
                            ra = shift_ra(ra)
                            y = dec_to_y(dec)
                            x = RA_to_x(g_share.x0, ra)
                            
                            #x,y = ra_dec_to_xyplot(ra, dec,xc,yc,rr)
                            dts.append((x,y))
                            
                            ra_dec_xs.add(i,j,ra,dec)
                        
                        dtss[i].append(dts)
                        
                        j+=1
                        #draw.polygon(dts, outline=(0,0,0,0),width=1)                  
                    #break
                #break
        #break         
    ra_dec_xs.commit('raxs_%d_%d')
    # milky way color
    mwc={
    1: (240,240,240,255),
    2: (230,230,230,255),
    3: (220,220,220,255),
    4: (210,210,210,255),
    5: (200,200,200,255),
    }
    dtss1= dtss[1]
    #print('dtss1[1]:%s' % dtss1[1])
    #draw.polygon(dtss1[0], outline=RED) #fill=mwc[1])
    #draw.polygon(dtss1[1], outline=BLUE) #fill=YELLOW) #(255,255,255,255))
    raxs_1_data = get_raxs_1_data()
    draw.polygon(raxs_1_data, fill=mwc[1])
    #raxs_0_data = get_raxs_0_data()
    #draw.polygon(raxs_0_data, outline=BLUE, width=2)
    
    dicts =get_raxs_n_data()
    raxs_1_n_data, segs = dicts[1]
    
    #raxs_1_n_data = get_raxs_1_n_data()
    for dts in raxs_1_n_data:
        draw.polygon(dts, fill=color_sky) #(255,255,255,255))

    for i in [2,3,4,5]:
        raxs_data,segs = dicts[i]
        for dts in raxs_data:
            if len(dts) < 3:
                continue
            draw.polygon(dts, fill=mwc[i]) #(255,255,255,255))
             
    skip="""    
    raxs_2_n_data, segs = dicts[2]
    #raxs_2_n_data,segs = get_raxs_2_n_data()
    print('len raxs_2_n:%d' % len(raxs_2_n_data))
    for dts in raxs_2_n_data:
        draw.polygon(dts, fill=mwc[2]) #(255,255,255,255))
    
    """
    skip="""
    for dts in dtss1[2:]:
        draw.polygon(dts, fill=color_sky) #(255,255,255,255))
    
    dtss2 = dtss[2]
    for dts in dtss2:
        draw.polygon(dts, fill=mwc[2])
    
    
    dtss3 = dtss[3]
    for dts in dtss3:
        draw.polygon(dts, fill=mwc[3])
     """   
    skip="""
    dtss4 = dtss[4]
    for dts in dtss4:
        draw.polygon(dts, fill=mwc[4])

    dtss5 = dtss[5]
    for dts in dtss5:
        draw.polygon(dts, fill=mwc[5])

    """	